<template>
	<view class="house-repair">
		<view class="repair">报修房屋</view>

		<view class="house-name">
			<u-action-sheet :actions="list" :title="title" :show="show" :closeOnClickAction="true" round="15"
				cancelText="取消" @close="onClose" @select="selectClick">
			</u-action-sheet>
			<u-button @click="show = true">{{houseName}}
				<u-icon name="arrow-right"></u-icon>
			</u-button>
		</view>

		<view class="repair">报修信息</view>

		<view class="repair-item">
			<u--form labelPosition="left" :model="form" :rules="rules" ref="form1">
				<u-form-item label="维修项目" @click="showRepair = true" prop="repairItemId" ref="item1">
					<u--input v-model="repairItem" placeholder="请选择" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="手机号码" prop="mobile" ref="item1">
					<u--input v-model="form.mobile" border="none" placeholder="请输入联系电话号码"></u--input>
				</u-form-item>
				<u-form-item label="预约日期" prop="appointment" borderBottom @click="showPicker = true" ref="item1">
					<u--input v-model="form.appointment" placeholder="请选择上门维修日期" border="none"></u--input>
					<u-icon slot="right" name="arrow-right"></u-icon>
				</u-form-item>
				<u-form-item label="问题描述" prop="description" labelPosition="top">
					<u--textarea v-model="form.description" placeholder="请填写详细报修内容，有助于工作人员快速帮您解决问题。" border="none">
					</u--textarea>
				</u-form-item>
				<u-form-item label="问题附件" prop="attachment" labelPosition="top">
					<u-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1" multiple
						:maxCount="5" uploadIcon="plus"></u-upload>
				</u-form-item>
			</u--form>
		</view>
		<u-action-sheet :show="showRepair" :actions="actions" title="选择维修项目" @close="showRepair = false"
			@select="repairSelect" cancelText="取消">
		</u-action-sheet>

		<u-datetime-picker ref="datetimePicker" :show="showPicker" title="选择上门日期" v-model="value1" mode="date"
			:formatter="formatter" @cancel="showPicker = false" @confirm="onConfirm"></u-datetime-picker>

		<life-button icon="../../static/icon/repair.png" @click="onSubmit">提交报修</life-button>
	</view>
</template>

<script>
	import {
		getRepairHouse,
		getRepairItem,
		submitRepair
	} from '../../api/house';
	export default {
		data() {
			return {
				title: '选择报修房屋',
				show: false,
				list: [],
				houseName: '北京西三旗花园1号楼 101',
				actions: [],
				showRepair: false,
				houseId: '',
				form: {
					repairItemId: '',
					mobile: '',
					appointment: '',
					description: '',
					attachment: []
				},
				repairItem: '',
				rules: {
					repairItemId: [{
						required: true,
						message: '请选择维修项目',
						trigger: ['blur', 'change']
					}],
					mobile: [{
							required: true,
							message: '请输入手机号',
							trigger: ['blur', 'change']
						},
						{
							pattern: /^(?:(?:\+|00)86)?1[3-9]\d{9}$/,
							message: '手机号格式不正确',
							trigger: ['blur', 'change']
						}
					],
					appointment: [{
						type: 'string',
						required: true,
						message: '请选择维修时间',
						trigger: ['blur', 'change']
					}],
					description: [{
						required: true,
						message: '请填写报修内容',
						trigger: ['blur', 'change']
					}]
				},
				showPicker: false,
				value1: Number(new Date()),
				fileList1: []
			};
		},
		onLoad() {
			this.getRepairHouse()
			this.getRepairItem()
		},
		onShow() {

		},
		onReady() {
			// 微信小程序需要用此写法
			this.$refs.datetimePicker.setFormatter(this.formatter)
			//如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
			this.$refs.form1.setRules(this.rules)
		},
		methods: {
			async onSubmit() {
				try {
					await this.$refs.form1.validate()
					const res = await submitRepair({
						houseId: this.houseId,
						...this.form
					})
					console.log(res)
				} catch (e) {
					//TODO handle the exception
					console.log(e)
				}
			},
			async getRepairHouse() {
				const {
					data
				} = await getRepairHouse()
				console.log('house', data)
				this.list = data
				this.houseName = data[0]?.name
				this.houseId = data[0]?.id
			},
			async getRepairItem() {
				const res = await getRepairItem()
				// console.log(res)
				this.actions = res.data
			},
			onClose() {
				this.show = false
			},
			selectClick(index) {
				// console.log(index)
				this.houseId = index.id
				this.houseName = index.name
			},
			repairSelect(e) {
				// console.log(e)
				this.form.repairItemId = e.id
				this.repairItem = e.name
				this.$refs.form1.validateField('repairItemId')
			},
			formatter(type, value) {
				if (type === 'year') {
					return `${value}年`
				}
				if (type === 'month') {
					return `${value}月`
				}
				if (type === 'day') {
					return `${value}日`
				}
				return value
			},
			onConfirm(e) {
				const timeFormat = uni.$u.timeFormat;
				// console.log(timeFormat(e.value, 'yyyy-mm-dd'))
				this.form.appointment = timeFormat(e.value, 'yyyy-mm-dd')
				this.$refs.form1.validateField('appointment')
				// console.log(e)
				this.showPicker = false
				// console.log(this.repairDate)
			},
			// 删除图片
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: 'https://live-api.itheima.net/upload',
						header: {
							Authorization: 'Bearer ' + this.$store.state.user.userToken.token
						},
						filePath: url,
						name: 'file',
						formData: {
							'Content-Type': 'multipart/form-data'
						},
						success: (res) => {
							setTimeout(() => {
								resolve(res.data.data)
								console.log(JSON.parse(res.data))
								this.form.attachment.push(JSON.parse(res.data).data)
								console.log(this.form.attachment)
							}, 1000)
						}
					});
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.house-repair {
		// height: 100%;
		background-color: #fafafa;
		padding-bottom: 275rpx;

		.repair {
			padding: 0 30rpx;
			line-height: 86rpx;
			color: #979797;
			font-size: 24rpx;
		}

		.house-name {
			font-size: 28rpx;
		}

		::v-deep .u-button--info {
			height: 102rpx;
			border: none;
		}

		::v-deep .u-button {
			justify-content: space-between;
		}

		// .repair-item {
		// 	padding: 0 30rpx;
		// }
		::v-deep .u-form {
			font-size: 28rpx;
			padding: 0 30rpx;
			background-color: #fff;

			// .u-form-item__body {
			// 	// height: 102rpx;
			// 	// padding: 0;
			// }
			.u-textarea {
				padding: 20rpx 0;

			}

			.u-upload {
				margin-top: 20rpx;
			}

			.u-textarea__field {
				height: 84rpx !important;
			}

			.u-line {
				border: none !important;
			}

			.u-form-item__body__left {
				width: 208rpx !important;
			}
		}

		::v-deep .u-toolbar {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

	}
</style>
